package dataClean;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Smartloe
 * @create 2021-05-20 19:34
 */
public class Txt2Csv {
    public static void main(String[] args) throws Exception{
        Character separator = ',';

        //从CSV中读取数据
        String fileName1 = "C:\\Users\\25392\\Desktop\\Java基础\\src\\main\\java\\dataClean\\data\\test.csv";
        readFromCSV(separator,fileName1);

        //向CSV中写入数据
        String fileName2 = "C:\\Users\\25392\\Desktop\\Java基础\\src\\main\\java\\dataClean\\data\\test.csv";
        List<String> str = new ArrayList<>();
        str.add("zhangsan");
        str.add("大数据1801");
        str.add("22");
        List<List<String>> strList = new ArrayList<>();
        strList.add(str);
//        writeIntoCSV(separator,fileName2,strList);

    }

    /**
     * Read from CSV
     *
     * @param separator 分隔符
     * @param filePath 文件路径 */
    public static<T> void readFromCSV(Character separator, String filePath) {
        CsvReader reader = null;
        List<T> result = new ArrayList<>();
        try {
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            reader = new CsvReader(filePath, separator, StandardCharsets.UTF_8);

            // 逐条读取记录，直至读完
            while (reader.readRecord()) {
                //读取第一例
                System.out.println(reader.get(0)+"|"+reader.get(1)+"|"+reader.get(2));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

    }




    /**
     * Write into CSV
     *
     * @param separator 分隔符
     * @param filePath 文件路径
     * @param strList 对应CSV中的一行记录
     * */
    public static void writeIntoCSV(Character separator, String filePath, List<List<String>> strList) {
        CsvWriter csvWriter = null;
        try {
            // 创建CSV写对象
            csvWriter = new CsvWriter(filePath, separator, StandardCharsets.UTF_8);
            // 写标题
            String[] headers = {"FileName","FileSize","FileMD5"};
            csvWriter.writeRecord(headers);
            for (List<String> list : strList) {
                String[] writeLine = new String[list.size()];
                list.toArray(writeLine);
                csvWriter.writeRecord(writeLine);
            }

            csvWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != csvWriter) {
                csvWriter.close();
            }
        }
    }

}
